/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018/11/21 Time: 10:06
 *
 * 个人中心
 */

import React, {Component} from 'react';
import {
    Linking,
    SafeAreaView, ScrollView, TouchableOpacity, View, TouchableHighlight, Text, Platform, BackHandler, ToastAndroid,
} from 'react-native';
import {connect} from 'react-redux';
import {Row, Rows, Table} from 'react-native-table-component';
import {styles} from './StaffAdd.Style';
import {retrieveWhskShifts, retrieveWHSKShiftsArrangeDefault, shiftsArrangeAdd} from "./Actions";
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {doDisplayWarnMessage} from "../../../component/Message/Action";
import AntDesign from "react-native-vector-icons/AntDesign";
import BottomButtonView from "../../../component/BottomButtonView/BottomButtonView";
import {COLOR_FOCUS, COLOR_GRAY_BACKGROUND, COLOR_LINK, FONT_COLOR_SUB_TITLE} from "../../../constant/PHColors";
import Entypo from "react-native-vector-icons/Entypo";
import DividingLineViewComponent from "../../../component/DividingLineViewComponent/DividingLineViewComponent";
import SelectPlaceTwoWheelPlugIn from "../../custom/selectDateTime/selectPlaceTwoWheelPlugIn";


class StaffAdd extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: navigation.getParam('headerTitle'),
    });

    // 构造
    constructor(props) {
        super(props);

        let date = new Date();
        let year = date.getFullYear().toString();
        let month = (date.getMonth()+1).toString();
        month = month.padStart(2,'0');
        let day = date.getDate().toString();
        day = day.padStart(2,'0');
        let opdate = year+'-'+month+'-'+day;

        // 初始状态
        this.state = {
            shift:this.props.navigation.getParam("shift")?this.props.navigation.getParam("shift"):"早班",
            opdate:this.props.navigation.getParam("opdate")?this.props.navigation.getParam("opdate"):opdate,
            usertype:this.props.navigation.getParam("usertype")?this.props.navigation.getParam("usertype"):"清洁人",
            callBack:this.props.navigation.getParam("callBack"),
            ds_alinusers:[],
            ds_place:{},
            checkedUser:{},
        };

        this.pinin='';
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;


        if (nextProps.onWHSKShiftsArrangeDefault !== this.props.onWHSKShiftsArrangeDefault && nextProps.onWHSKShiftsArrangeDefault.fetchStatus === FetchStatus.Success) {
            if (nextProps.onWHSKShiftsArrangeDefault.RETURN === ReturnStatus.Success) {
                let alinusers = nextProps.onWHSKShiftsArrangeDefault.alinusers;
                let place = nextProps.onWHSKShiftsArrangeDefault.place;

                let place_json = {};
                place.map((item,value)=>{
                    if(place_json[item.name]){
                        place_json[item.name].push(item)
                    }else{
                        place_json[item.name] = [item]
                    }
                })

                this.setState({
                    ds_alinusers:alinusers,
                    ds_place:place_json
                })
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onWHSKShiftsArrangeDefault.MSG))
            }
        }


        if (nextProps.onShiftsArrangeAdd !== this.props.onShiftsArrangeAdd && nextProps.onShiftsArrangeAdd.fetchStatus === FetchStatus.Success) {
            if (nextProps.onShiftsArrangeAdd.RETURN === ReturnStatus.Success) {
                ToastAndroid.show(nextProps.onShiftsArrangeAdd.MSG, 500);//提示
                this.props.navigation.state.params.callBack()
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onWHSKShiftsArrangeDefault.MSG))
            }
        }

    }

    componentDidMount() {
        let {dispatch} = this.props;

        this.props.navigation.setParams({"headerTitle": "添加"+this.state.shift+"人员"});

        let str = {"arg":{"opdate":this.state.opdate,"shift":this.state.shift,"usertype":this.state.usertype}};
        dispatch(retrieveWHSKShiftsArrangeDefault(JSON.stringify(str)));
    }

    render() {
        let {dispatch} = this.props;

        return (
            <SafeAreaView style={styles.container} >
                <ScrollView style={styles.body}>
                    <View >
                        {
                            this.state.ds_alinusers.map((value,index)=>{
                                return(
                                    this.showAlinusersList(value,index)
                                )

                            })
                        }

                    </View>
                </ScrollView>
                <BottomButtonView title={'保存'} onSubmitClick={() => {
                    let checked_json = this.state.checkedUser;
                    let json_array = [];
                    for(let userid in checked_json){
                        let json = {"opdate":this.state.opdate,"shift":this.state.shift,"wuserid":checked_json[userid]['wuserid'],"place":checked_json[userid]['place'],"position":this.state.usertype}
                        json_array.push(json)
                    }
                    let str = {"whsk_shifts_arrange":json_array};
                    console.log(JSON.stringify(str))

                    let {dispatch} = this.props;
                    dispatch(shiftsArrangeAdd(JSON.stringify(str)));
                }}/>
            </SafeAreaView>
        )
    };

    showAlinusersList=(value,index)=>{
        let html_arr = [];

        if(value.groupby!==this.pinin){
            let html_title = (
                <View key={'title_'+index} style={[styles.itemHeader,{backgroundColor:COLOR_GRAY_BACKGROUND,height:32}]}>
                    <View style={styles.itemHeaderLeft}>
                        <Text style={styles.itemHeaderText}>
                            {value.groupby}
                        </Text>
                    </View>
                </View>
            )
            html_arr.push(html_title)
        }

        let html_user = (
            <TouchableOpacity activeOpacity={0.9} onPress={()=> {
                let checkedUser = this.state.checkedUser;

                if(checkedUser[value.code]){
                    delete checkedUser[value.code]
                }else{
                    checkedUser[value.code] = {"wuserid":value.code,"place":"",};
                }

                this.setState({
                    checkedUser:checkedUser,
                })
            }}>
                <View key={'title_'+index} style={styles.itemHeader}>
                    <View style={styles.itemHeaderLeft}>
                        {
                            (this.state.checkedUser[value.code] )
                                ?
                                (<AntDesign name={'checkcircle'} size={23} style={{color: COLOR_FOCUS, marginLeft: 10}} />)
                                :
                                (<Entypo name={'circle'} size={23} style={{color: '#b3b9ba', marginLeft: 10}} />)
                        }
                        <Text style={styles.itemHeaderText}>
                            {value.name+'-'+value.code}
                        </Text>
                    </View>
                    <View style={styles.itemHeaderRight}>
                        {
                            (this.state.checkedUser[value.code] )
                                ?
                                (
                                    <SelectPlaceTwoWheelPlugIn defaultPlace={'选择地点'} defaultDate={this.state.ds_place} textStyle={styles.opdateViewStyle} dateBack={(date)=>{
                                        let reg = new RegExp("层","g");
                                        let place =(date.replace(reg,""));
                                        this.state.checkedUser[value.code]['place'] = place;
                                    }} />
                                )
                                :
                                (
                                    <Text style={styles.itemHeaderText}>

                                    </Text>
                                )
                        }
                    </View>
                </View>
                <DividingLineViewComponent lineHeight={1}/>
            </TouchableOpacity>
        )
        html_arr.push(html_user);

        if( (Number(index)+1) === this.state.ds_alinusers.length){
            this.pinin = '';
        }else{
            this.pinin = value.groupby;
        }

        return html_arr
    };

    showPlaceList=(value,index)=>{

    };
}

const props = state => {
    return {
        onWHSKShiftsArrangeDefault:state.onWHSKShiftsArrangeDefault,
        onShiftsArrangeAdd:state.onShiftsArrangeAdd,
    }
};

export default StaffAdd = connect(props)(StaffAdd);